package com.cakin.filter;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;

/**
 * @ClassName: CharacterEncodingFilter
 * @Description: 解决中文乱码问题
 * @Date: 2020/6/14
 * @Author: cakin
 */
public class CharacterEncodingFilter implements Filter {
    /**
     * 功能描述：初始化
     *
     * @author cakin
     * @date 2020/6/14
     * @param filterConfig 过滤器配置
     * @throws ServletException ServletException
     * @description: web启动就会初始化，同Tomcat一起启动
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter 初始化");
    }

    /**
     * 功能描述：过滤器核心方法
     *
     * @param request  请求
     * @param response 响应
     * @param chain    过滤器链
     * @throws IOException      IOException
     * @throws ServletException IOException
     * @author cakin
     * @date 2020/6/14
     * @description: 关键点
     * 1 针对特定的请求，过滤器会执行，这个特定的请求是在web.xml中配置过滤器
     * 2 为了让程序继续往下走，必须执行 chain.doFilter(request, response);
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 处理乱码问题
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("执行前");
        // 让我们的程序继续往下走，否则程序就在这里停止了
        chain.doFilter(request, response);
        System.out.println("执行后");
    }
    /**
     * 功能描述：过滤器销毁
     *
     * @author cakin
     * @date 2020/6/14
     * @description: web服务器停止时，会执行这个函数
     */
    public void destroy() {
        System.out.println("CharacterEncodingFilter 销毁");
    }
}
